package com.avecsys.quotemanager.mbeans.system;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icefaces.ace.json.JSONException;
import org.icefaces.ace.json.JSONObject;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.constants.BusinessCodes;
import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.CompanyMasterPojo;
import com.avecsys.quotemanager.pojos.SystemUsersPojo;
import com.avecsys.quotemanager.service.common.CommonService;
import com.avecsys.quotemanager.service.system.SystemUserService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.SystemConfig;
import com.avecsys.quotemanager.utils.TransactionStatus;

public class SystemUsersListMBean extends BaseMBean implements Serializable {
	private final Log log = LogFactory.getLog(SystemUsersListMBean.class);

	private CompanyMasterPojo selectedCompany;

	private SystemUserService systemUserService;

	private UserMasterService userMasterService;

	private CommonService commonService;

	private List<SystemUsersPojo> systemUsersPojoList = new ArrayList<SystemUsersPojo>();

	public SystemUsersListMBean() {
		super();
	}

	/**
	 * Action method to open the add user screen for a system
	 * 
	 * @return String
	 */
	public String actionAddUser() {
		try{
			FacesContext faceContext = FacesContext.getCurrentInstance();
			CompanyMasterPojo companyMasterPojo = systemUserService.getCompanyMasterForSystem();
			String companyId = companyMasterPojo.getCompanyId().toString();
			String companyName = companyMasterPojo.getCompanyName();
			SystemUsersMBean systemUsersMBean = (SystemUsersMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{systemUsersMBean}", SystemUsersMBean.class);
			systemUsersMBean.setSelectedCompanyId(companyId);
			systemUsersMBean
					.setSelectedSystemCompanyName(companyName);
			systemUsersMBean.setSystemUsersPojo(new SystemUsersPojo());
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openAddUserForSystem";
	}

	/**
	 * Method to delete the selected system user
	 * 
	 * @param actionEvent
	 */
	public void actionDeleteSystemUser(ActionEvent actionEvent) {
		MessageBoardUtil.resetMessageBoard();
		String requestJSON = getMessageDialog().getRequestJSON();
		JSONObject requestJSONObject;
		String systemUserId = null;
		try {
			requestJSONObject = new JSONObject(requestJSON);
			systemUserId = (String) requestJSONObject.get("systemUserId");
			SystemUsersPojo systemUsersPojo = userMasterService
					.getSystemUserById(new Long(systemUserId));
			TransactionStatus transactionStatus = userMasterService
					.deleteSystemUser(systemUsersPojo);
			loadAllUsers();
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.SYSTEM_USER, "messageBoardId", "",
					new Object[] { systemUsersPojo.getUserMasterPojo()
							.getUserName() });
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		getMessageDialog().hideDialog();
	}

	/**
	 * Action Method to send verification email to System user
	 * 
	 * @param actionEvent
	 */
	public void actionSendVerificationEmail(ActionEvent actionEvent) {
		MessageBoardUtil.resetMessageBoard();
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String systemUserId = (String) paramValues.get("systemUserId");
		SystemUsersPojo systemUsersPojo = null;
		try {
			systemUsersPojo = userMasterService.getSystemUserById(new Long(
					systemUserId));
			// Send Verification Email only when if it is not already verified
			commonService.sendEmail(systemUsersPojo);
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		try {
			if (systemUsersPojo != null) {
				loadAllUsers();
			}
		} catch (BusinessException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	/**
	 * Method to show the confirm dialog request to delete system user
	 * 
	 * @param actionEvent
	 */
	public void confirmDeleteAction(ActionEvent actionEvent) {
		try 
		{
			FacesContext faceContext = FacesContext.getCurrentInstance();
			Map<String, String> paramValues = faceContext.getExternalContext()
					.getRequestParameterMap();
			String systemUserId = (String) paramValues.get("systemUserId");
			 
			CompanyMasterPojo companyMasterPojo = systemUserService.getCompanyMasterForSystem();
			
			String selectedCompanyId = companyMasterPojo.getCompanyId().toString();
			String userName = (String) paramValues.get("userName");
			JSONObject requestJSONObject = new JSONObject();
			try {
				requestJSONObject.put("companyId", selectedCompanyId);
				requestJSONObject.put("systemUserId", systemUserId);
				requestJSONObject.put("systemUserName", userName);
				getMessageDialog().setRequestJSON(requestJSONObject.toString());
				getMessageDialog().setMessage(
						"Are you sure to delete '" + userName + "' ?");
			} catch (JSONException e) {
				log.error(e);
			}
		} catch (BusinessException e1) {
			log.error(e1);
		}
		getMessageDialog().showDialog();
	}

	/**
	 * Edits the system user information
	 * 
	 * @return
	 */
	public String editSystemUser() {
		try {
			FacesContext faceContext = FacesContext.getCurrentInstance();
			Map<String, String> paramValues = faceContext.getExternalContext()
					.getRequestParameterMap();
			CompanyMasterPojo companyMasterPojo = systemUserService.getCompanyMasterForSystem();
			String companyId = companyMasterPojo.getCompanyId().toString();
			String companyName = companyMasterPojo.getCompanyName();
			String systemUserId = (String) paramValues.get("systemUserId");
			
			SystemUsersMBean systemUsersMBean = (SystemUsersMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{systemUsersMBean}", SystemUsersMBean.class);
			systemUsersMBean.setSelectedCompanyId(companyId);
			systemUsersMBean
					.setSelectedSystemCompanyName(companyName);
			SystemUsersPojo systemUsersPojo = userMasterService
					.getSystemUserById(Long.parseLong(systemUserId));
			systemUsersMBean.setSystemUsersPojo(systemUsersPojo);
			// preserve the the email address to identify user has changed the
			// email address
			systemUsersMBean.setExistingEmailAddress(systemUsersPojo
					.getUserMasterPojo().getEmail());
			systemUsersMBean.setScreenModeEdit(true);
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		return "openEditUserForSystem";
	}

	public CommonService getCommonService() {
		return commonService;
	}

	/**
	 * @return the selectedSystem
	 */
	public CompanyMasterPojo getSelectedCompany() {
		return selectedCompany;
	}

	/**
	 * @return the systemMasterService
	 */
	public SystemUserService getSystemUserService() {
		return systemUserService;
	}

	public List<SystemUsersPojo> getSystemUsersPojoList() {
		return systemUsersPojoList;
	}
	
	public void init() {
		try{
			loadAllUsers();
		} catch (BusinessException e) {
			log.error(e);
		}
	}

	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	/**
	 * Method to load all the users for a system
	 * 
	 * @param systemMasterPojo
	 * @throws BusinessException
	 */
	public void loadAllUsers()
			throws BusinessException {
		setSystemUsersPojoList(systemUserService.getAllUsers());
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param selectedSystem
	 *            the selectedSystem to set
	 */
	public void setSelectedCompany(CompanyMasterPojo selectedCompany) {
		this.selectedCompany = selectedCompany;
	}

	/**
	 * @param systemMasterService
	 *            the systemMasterService to set
	 */
	public void setSystemUserService(
			SystemUserService systemUserService) {
		this.systemUserService = systemUserService;
	}

	public void setSystemUsersPojoList(
			List<SystemUsersPojo> systemUsersPojoList) {
		this.systemUsersPojoList = systemUsersPojoList;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}
}
